package com.cskaoyan.controller.weixin_zyl;

import com.cskaoyan.bean.bo.Weixin_Cart_zylBO.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.marketBean.*;
import com.cskaoyan.bean.vo.weixin_zyl_VO.Weixin_zyl_checkout;
import com.cskaoyan.bean.vo.weixin_zyl_VO.Weixin_zyl_index_Vo;
import com.cskaoyan.service.Zyl_Shopping_cart_Service.MarketCartService_zyl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("wx/cart")
public class Shopping_cart_Controller {


    @Autowired
    MarketCartService_zyl marketCartService_zyl;


    @RequestMapping("index")
    public Weixin_zyl_index_Vo index() {
        //伪id
        //Integer user_id = 1;
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer user_id = primaryPrincipal.getId();

       /* MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andUserIdEqualTo(user_id);
        marketCartExample.createCriteria().andDeletedEqualTo(true);

        List<MarketCart> marketCarts = marketCartService_zyl.selectByExample(marketCartExample);*/

        List<MarketCart> marketCarts = marketCartService_zyl.selectByExample_zyl(user_id, true);

//primaryPrincipal  个人信息
       /*
        System.out.println("primaryPrincipal = " + primaryPrincipal);*/
        Integer goodsCount = 0;
        Integer checkedGoodsCount = 0;
        Integer goodsAmount = 0;
        Integer checkedGoodsAmount = 0;
        for (MarketCart marketCart : marketCarts) {
            goodsCount += marketCart.getNumber();
            goodsAmount += marketCart.getNumber() * (marketCart.getPrice().intValue());
            ;
            if (marketCart.getChecked()) {
                checkedGoodsAmount += marketCart.getNumber() * (marketCart.getPrice().intValue());
                checkedGoodsCount += marketCart.getNumber();
            }
        }
        Weixin_zyl_index_Vo weixin_zyl_index_vo = new Weixin_zyl_index_Vo();
        Weixin_zyl_index_Vo.DataDTO dataDTO = new Weixin_zyl_index_Vo.DataDTO();
        Weixin_zyl_index_Vo.DataDTO.CartTotalDTO cartTotalDTO = new Weixin_zyl_index_Vo.DataDTO.CartTotalDTO();
        cartTotalDTO.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotalDTO.setCheckedGoodsCount(checkedGoodsCount);
        cartTotalDTO.setGoodsAmount(goodsAmount);
        cartTotalDTO.setGoodsCount(goodsCount);
        dataDTO.setCartList(marketCarts);
        dataDTO.setCartTotal(cartTotalDTO);
        weixin_zyl_index_vo.setData(dataDTO);
        weixin_zyl_index_vo.setErrmsg("成功");
        weixin_zyl_index_vo.setErrno(0);
        return weixin_zyl_index_vo;
    }

    @PostMapping("checked")
    public Weixin_zyl_index_Vo checked(@RequestBody Weixin_car_checket weixin_car_checket) {

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer user_id = primaryPrincipal.getId();


        Integer isChecked = weixin_car_checket.getIsChecked();
        List<Integer> productIds = weixin_car_checket.getProductIds();
        for (Integer productId : productIds) {
            marketCartService_zyl.updateMarketCart_zyl(productId, isChecked, user_id);
        }

        return index();
    }


    @PostMapping("update")
    public BaseRespVo update(@RequestBody Weixin_car_update weixin_car_update) {

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer user_id = primaryPrincipal.getId();

        MarketCart marketCart = new MarketCart();
        marketCartService_zyl.update_zyl(weixin_car_update.getProductId(), weixin_car_update.getGoodsId(), weixin_car_update.getNumber(), weixin_car_update.getId(), user_id);
        return BaseRespVo.ok("ok");
    }

    @RequestMapping("checkout")
    public Weixin_zyl_checkout checkout(Weixin_car_checkout weixin_car_checkout) {
        Subject subject = SecurityUtils.getSubject();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer user_id = primaryPrincipal.getId();

        Session session = subject.getSession();

        List<Integer> cartid = new ArrayList<>();
        if (weixin_car_checkout.getCartId() == 0) {
            Integer goodsTotalPrice = 0;
            MarketAddress marketAddress = marketCartService_zyl.selectByPrimaryKey(weixin_car_checkout.getAddressId());

            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(user_id);
            criteria.andCheckedEqualTo(false);
            List<MarketCart> marketCarts = marketCartService_zyl.selectByExample(marketCartExample);
            int count = 0;
            for (MarketCart marketCart : marketCarts) {
                //marketCart.getNumber() * (marketCart.getPrice().intValue());
                cartid.add(marketCart.getId());
                count++;
                goodsTotalPrice += marketCart.getNumber() * (marketCart.getPrice().intValue());
            }

            //couponPrice优惠卷
            MarketCouponUser marketCouponUser = marketCartService_zyl.selectByPrimaryKey_zyl_couponuser(user_id);
            Integer couponId =0;
            if (marketCouponUser != null) {
                couponId=marketCouponUser.getCouponId();
            }

            MarketCoupon marketCoupon = marketCartService_zyl.selectByPrimaryKey_zyl_coupon(couponId);
            Integer couponPrice=0;
            if (marketCoupon != null) {
                BigDecimal discount = marketCoupon.getDiscount();
                couponPrice= discount.intValue();
            }

            Integer grouponPrice = 0;
            MarketOrderExample marketOrderExample = new MarketOrderExample();
            MarketOrderExample.Criteria criteria1 = marketOrderExample.createCriteria();
            criteria1.andUserIdEqualTo(user_id);
            if(marketCouponUser!=null){
                criteria1.andIdEqualTo(marketCouponUser.getOrderId());
            }

            int FreightPrice = 0;

            List<MarketOrder> marketOrders = marketCartService_zyl.selectByExample(marketOrderExample);
            for (MarketOrder marketOrder : marketOrders) {
                grouponPrice += marketOrder.getCouponPrice().intValue();
                FreightPrice += marketOrder.getFreightPrice().intValue();
            }
            //actualPrice
            Integer actualPrice = 0;
            if (goodsTotalPrice < (couponPrice + grouponPrice)) {
                actualPrice = 0;
            } else {
                actualPrice = goodsTotalPrice - couponPrice;
            }
//grouponRulesId
            //marketCartService_zyl.select_zyl()

            Weixin_zyl_checkout.DataDTO dataDTO = new Weixin_zyl_checkout.DataDTO();
            dataDTO.setGrouponRulesId(0);
            dataDTO.setActualPrice(actualPrice);
            dataDTO.setOrderTotalPrice(actualPrice);
            dataDTO.setCartId(1);
            dataDTO.setUserCouponId(0);
            dataDTO.setCouponId(0);
            dataDTO.setGoodsTotalPrice(goodsTotalPrice);
            // TODO 记得改回来
            dataDTO.setAddressId(weixin_car_checkout.getAddressId());
            // 为了方便测试代码
            //dataDTO.setAddressId(1);
            dataDTO.setFreightPrice(FreightPrice);
            dataDTO.setGrouponPrice(grouponPrice);
            dataDTO.setCheckedAddress(marketAddress);
            dataDTO.setCouponPrice(couponPrice);
            dataDTO.setAvailableCouponLength(count);
            dataDTO.setCheckedGoodsList(marketCarts);
            Weixin_zyl_checkout weixin_zyl_checkout = new Weixin_zyl_checkout();
            weixin_zyl_checkout.setErrmsg("成功");
            weixin_zyl_checkout.setErrno(0);
            weixin_zyl_checkout.setData(dataDTO);

            session.setAttribute("cartid", cartid);
            return weixin_zyl_checkout;

        } else {

            Weixin_car_add fastadd = (Weixin_car_add) session.getAttribute("fastadd");
            Integer goodsId = fastadd.getGoodsId();
            Integer productId = fastadd.getProductId();
            Integer number = fastadd.getNumber();
            Date date = (Date) session.getAttribute("date");


            Integer goodsTotalPrice = 0;
            MarketAddress marketAddress = marketCartService_zyl.selectByPrimaryKey(weixin_car_checkout.getAddressId());

            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(user_id);
            // criteria.andIdEqualTo(weixin_car_checkout.getCartId());
            criteria.andGoodsIdEqualTo(goodsId);
            criteria.andProductIdEqualTo(productId);
            criteria.andNumberEqualTo(number.shortValue());
            // criteria.andAddTimeEqualTo(date);
            criteria.andCheckedEqualTo(true);
            List<MarketCart> marketCarts = marketCartService_zyl.selectByExample(marketCartExample);
            int count = 0;
            for (MarketCart marketCart : marketCarts) {
                //marketCart.getNumber() * (marketCart.getPrice().intValue());
                //System.out.println("marketCart = " + marketCart);
                cartid.add(marketCart.getId());
                count++;
                goodsTotalPrice += marketCart.getNumber() * (marketCart.getPrice().intValue());
            }

            //couponPrice优惠卷
            MarketCouponUser marketCouponUser = marketCartService_zyl.selectByPrimaryKey_zyl_couponuser(user_id);

            Integer couponPrice = 0;
            if(marketCouponUser!=null){
                Integer couponId = marketCouponUser.getCouponId();
                MarketCoupon marketCoupon = marketCartService_zyl.selectByPrimaryKey_zyl_coupon(couponId);
                BigDecimal discount = marketCoupon.getDiscount();
                couponPrice = discount.intValue();
            }


            Integer grouponPrice = 0;
            MarketOrderExample marketOrderExample = new MarketOrderExample();
            MarketOrderExample.Criteria criteria1 = marketOrderExample.createCriteria();
            criteria1.andUserIdEqualTo(user_id);

            if (marketCouponUser!=null){
                criteria1.andIdEqualTo(marketCouponUser.getOrderId());
            }


            //FreightPrice配送费

            int FreightPrice = 0;

            List<MarketOrder> marketOrders = marketCartService_zyl.selectByExample(marketOrderExample);
            for (MarketOrder marketOrder : marketOrders) {
                grouponPrice += marketOrder.getCouponPrice().intValue();
                FreightPrice += marketOrder.getFreightPrice().intValue();
            }
            //actualPrice
            Integer actualPrice = 0;
            if (goodsTotalPrice < (couponPrice + grouponPrice)) {
                actualPrice = 0;
            } else {
                actualPrice = goodsTotalPrice - couponPrice;
            }
//grouponRulesId
            //marketCartService_zyl.select_zyl()

            Weixin_zyl_checkout.DataDTO dataDTO = new Weixin_zyl_checkout.DataDTO();
            dataDTO.setGrouponRulesId(0);
            dataDTO.setActualPrice(actualPrice);
            dataDTO.setOrderTotalPrice(actualPrice);
            dataDTO.setCartId(0);
            dataDTO.setUserCouponId(0);
            dataDTO.setCouponId(0);
            dataDTO.setGoodsTotalPrice(goodsTotalPrice);
            dataDTO.setAddressId(weixin_car_checkout.getAddressId());
            dataDTO.setFreightPrice(FreightPrice);
            dataDTO.setGrouponPrice(grouponPrice);
            dataDTO.setCheckedAddress(marketAddress);
            dataDTO.setCouponPrice(couponPrice);
            dataDTO.setAvailableCouponLength(count);
            dataDTO.setCheckedGoodsList(marketCarts);
            Weixin_zyl_checkout weixin_zyl_checkout = new Weixin_zyl_checkout();
            weixin_zyl_checkout.setErrmsg("成功");
            weixin_zyl_checkout.setErrno(0);
            weixin_zyl_checkout.setData(dataDTO);


            return weixin_zyl_checkout;
        }
        //user_id=1

        //现在的价格actualPrice=goodsTotalPrice-couponPrice-grouponPrice
        //goodsTotalPrice


    }

    @PostMapping("delete")
    public Weixin_zyl_index_Vo delete(@RequestBody Weixin_cart_delete weixin_cart_delete) {


        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer user_id = primaryPrincipal.getId();


        List<Integer> productIds = weixin_cart_delete.getProductIds();
        for (Integer productId : productIds) {
            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andProductIdEqualTo(productId);
            marketCartExample.createCriteria().andUserIdEqualTo(user_id);
            marketCartService_zyl.deleteByExample(marketCartExample);
        }

        return index();
    }


    @PostMapping("add")
    public BaseRespVo add(@RequestBody Weixin_car_add weixin_car_add) {
        BaseRespVo baseRespVo = new BaseRespVo();

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer user_id = primaryPrincipal.getId();

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andProductIdEqualTo(weixin_car_add.getProductId());
        marketCartExample.createCriteria().andUserIdEqualTo(user_id);
        marketCartExample.createCriteria().andGoodsIdEqualTo(weixin_car_add.getGoodsId());
        List<MarketCart> marketCarts = marketCartService_zyl.selectByExample(marketCartExample);
        if (marketCarts.size() != 0) {
            MarketCart marketCart = marketCarts.get(0);
            Integer i = marketCart.getNumber().intValue();
            Integer number = i + weixin_car_add.getNumber();
            marketCart.setNumber(number.shortValue());
            marketCart.setAddTime(new Date());
            marketCart.setUpdateTime(new Date());
            marketCartService_zyl.updateByPrimaryKey(marketCart);
            baseRespVo.setData(goodscount().getData());
            baseRespVo.setErrno(0);
            baseRespVo.setErrmsg("成功");
            return baseRespVo;
        } else {


            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sa");
            String time = sdf.format(date);


            MarketGoods marketGoods = marketCartService_zyl.selectByPrimaryKey_zyl(weixin_car_add.getGoodsId());
            MarketGoodsProduct product = marketCartService_zyl.select_zyl(weixin_car_add.getProductId(), weixin_car_add.getGoodsId());
            MarketCart marketCart = new MarketCart();
            marketCart.setUserId(user_id);
            marketCart.setGoodsId(weixin_car_add.getGoodsId());
            marketCart.setGoodsSn(marketGoods.getGoodsSn());
            marketCart.setGoodsName(marketGoods.getName());
            marketCart.setProductId(weixin_car_add.getProductId());
            marketCart.setPrice(product.getPrice());
            marketCart.setNumber(weixin_car_add.getNumber().shortValue());
            marketCart.setSpecifications(product.getSpecifications());
            marketCart.setChecked(true);
            marketCart.setPicUrl(product.getUrl());
            marketCart.setAddTime(new Date());
            marketCart.setUpdateTime(new Date());
            marketCart.setDeleted(false);
            marketCartService_zyl.insert(marketCart);


            baseRespVo.setData(goodscount().getData());
            baseRespVo.setErrno(0);
            baseRespVo.setErrmsg("成功");
            return baseRespVo;
        }
    }

    @RequestMapping("goodscount")
    public BaseRespVo<Integer> goodscount() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer user_id = primaryPrincipal.getId();
        BaseRespVo<Integer> baseRespVo = new BaseRespVo<Integer>();
        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.createCriteria().andUserIdEqualTo(user_id);
        List<MarketCart> marketCarts = marketCartService_zyl.selectByExample(marketCartExample);
        int number = 0;
        if (marketCarts.size() != 0) {
            for (MarketCart marketCart : marketCarts) {
                number += marketCart.getNumber().intValue();
            }
        }
        baseRespVo.setData(number);
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }


    @PostMapping("fastadd")
    public BaseRespVo fastadd(@RequestBody Weixin_car_add weixin_car_add) {

        BaseRespVo baseRespVo = new BaseRespVo();

        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer user_id = primaryPrincipal.getId();


        Date date = new Date();

        MarketGoods marketGoods = marketCartService_zyl.selectByPrimaryKey_zyl(weixin_car_add.getGoodsId());
        MarketGoodsProduct product = marketCartService_zyl.select_zyl(weixin_car_add.getProductId(), weixin_car_add.getGoodsId());
        MarketCart marketCart = new MarketCart();
        marketCart.setUserId(user_id);
        marketCart.setGoodsId(weixin_car_add.getGoodsId());
        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setGoodsName(marketGoods.getName());
        marketCart.setProductId(weixin_car_add.getProductId());
        marketCart.setPrice(product.getPrice());
        marketCart.setNumber(weixin_car_add.getNumber().shortValue());
        marketCart.setSpecifications(product.getSpecifications());
        marketCart.setChecked(true);
        marketCart.setPicUrl(product.getUrl());
        marketCart.setAddTime(date);
        marketCart.setUpdateTime(new Date());
        marketCart.setDeleted(false);
        marketCartService_zyl.insert(marketCart);

        //存入session
        session.setAttribute("fastadd", weixin_car_add);
        session.setAttribute("date", date);


        baseRespVo.setData(weixin_car_add.getNumber());
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }
}




